package com.qyc.Microservice.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qyc.Microservice.dto.pojo.User;
import com.qyc.Microservice.mapper.UserMapper;
import com.qyc.Microservice.repository.UserRepository;

@Service
public class UserService {

	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private UserMapper userMapper;
	
	public User save(User user) {
		return userRepository.save(user);
	}
	
	public void saveMapper(User user) {
		 userMapper.insert(user);
	}
	
	public int updateMapper(User user) {
		return userMapper.update(user);
	}
	public int deleteMapper(User user) {
		return userMapper.delete(user);
	}
	public User selectMapper(User user) {
		return userMapper.select(user);
	}
	
	public User getUserByNameMybatis2(String name){
		return userMapper.getUserByName2("user",name,14);
	}
	
	public User getUserByNameMybatis3(User user){
		return userMapper.getUserByName3(user);
	}
	
	public User findByNameAndAge(String name, Integer age) {
		return userRepository.findByNameAndAge(name, age);
	}
	
	public List<User> getUserByAge(Integer age,int pageSize,int pageNum){
		
		return userRepository.findByAge(age, PageRequest.of(pageNum, pageSize));
	}
	
	public User findFirstByOrderByAgeAsc() {
	    return userRepository.findFirstByOrderByAgeAsc();
	}
	
	public List<User> findFirst3ByAge(Integer age){
		Order order = new Order(Direction.ASC,"name");
		Order order1 = new Order(Direction.DESC,"sex");
		List<Order> list = new ArrayList<Order>();
		list.add(order);
		list.add(order1);
		return userRepository.findFirst3ByAge(age, Sort.by(list));
	}
	
	public User getByNameAndAge(String name,Integer age) {
		return userRepository.getByNameAndAge(name, age);
	}
	
	//springboot与原来的hibernate和mybatis不太一样。他要求在对持久层修改的时候，一定要在事物环境中
	//这是强制的
	//@Transactional 只有遇到runtimeException的时候，才会进行事物控制和回滚
	@Transactional(rollbackFor =Exception.class) //只要有异常，就会进行异常的抛出和事物控制和回滚
	public void changePwd(String name,String oldPwd,String newPwd) {
		 userRepository.changePwd(name, oldPwd, newPwd);
	}
	
	public List<User> findByNameLike(String name){
		return userRepository.findByNameLike(name);
	}
	

}
